#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速连接和断开测试
用于测试客户端断开连接时的online状态更新
"""

import socket
import json
import time

def test_disconnect():
    print("开始快速连接和断开测试...")
    
    # 连接到服务器
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(('localhost', 8888))
        print("已连接到服务器")
        
        # 注册机器人
        register_msg = {
            "type": "register",
            "sn": "ROBOT_TEST_DISCONNECT",
            "version": "1.0.0",
            "model": "TestRobot"
        }
        
        json_data = json.dumps(register_msg, ensure_ascii=False)
        data = (json_data + '\n').encode('utf-8')
        sock.send(data)
        print(f"发送注册消息: {json_data}")
        
        # 等待响应
        time.sleep(1)
        try:
            response = sock.recv(1024)
            if response:
                print(f"收到响应: {response.decode('utf-8').strip()}")
        except:
            pass
        
        # 发送一条数据
        data_msg = {
            "type": "data",
            "timestamp": int(time.time() * 1000),
            "position": {
                "x": 10.0,
                "y": 20.0,
                "z": 30.0
            },
            "temperature": 25.5,
            "battery": 80,
            "status": "working"
        }
        
        json_data = json.dumps(data_msg, ensure_ascii=False)
        data = (json_data + '\n').encode('utf-8')
        sock.send(data)
        print(f"发送数据: {json_data}")
        
        # 等待一下，然后断开连接
        time.sleep(2)
        
    finally:
        sock.close()
        print("连接已断开")

if __name__ == "__main__":
    test_disconnect()